package experiment.networkmodel;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client implements Updatable, Runnable {

	private Scanner scan;
	protected int port;
	protected Socket serverSocket;
	protected volatile boolean quit;
	protected Thread t;
	protected SocketSpeaker listen;
	public Client(){
		scan = new Scanner(System.in);
		quit = false;
	}
	
	@Override
	public void run() {
		String userInput;
		
		System.out.println("Type in the port you would like to listen on: ");
		userInput = scan.next();
		port = Integer.parseInt(userInput);
		
		System.out.println("Type in the host name");
		try {
			serverSocket = new Socket(scan.next(), port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			run();
		} catch (IOException e) {
			e.printStackTrace();
		}
		

		listen = new SocketSpeaker(serverSocket, this);
		t = new Thread(listen);
		t.setDaemon(true);
		t.start();
	}

	@Override
	public void update(Object obj) {
		String temp = (String)obj;
		System.out.println(temp);
		
		System.out.print("Type a reply: ");
		temp = scan.nextLine();
	}

	@Override
	public void kill(int status) {
		quit = true;
		System.exit(status);
	}

}
